package cmd

import (
	"fmt"
	"os"

	"gitee.com/xuender/toolkit/hash"
	"github.com/spf13/cobra"
)

// nolint: gochecknoinits
func init() {
	hashCmd := &cobra.Command{
		Use:   "hash",
		Short: "摘要生成",
		Long: `对文本或文件生成摘要

摘要类型: md5, sha1, sha256, sha512。`,
		Run: func(cmd *cobra.Command, args []string) {
			t, _ := cmd.Flags().GetString("type")
			if len(args) == 0 {
				h, err := hash.Read(os.Stdin, hash.Type(t))
				if err == nil {
					fmt.Fprintf(os.Stdout, "%s  -\n", h)
				} else {
					fmt.Fprintf(os.Stdout, "%s\n", err)
				}

				return
			}

			for _, f := range args {
				h, err := hash.File(f, hash.Type(t))
				if err == nil {
					fmt.Fprintf(os.Stdout, "%s  %s\n", h, f)
				} else {
					fmt.Fprintf(os.Stdout, "%s  %s\n", err, f)
				}
			}
		},
	}
	rootCmd.AddCommand(hashCmd)
	hashCmd.Flags().StringP("type", "t", "md5", "摘要类型: md5, sha1, sha256, sha512")
}
